package com.ruoyi.system.service.impl;

import java.util.*;

import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ResultManagementMapper;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.stream.Collectors;

import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

/**
 * 四级联考终审结果Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class ResultManagementServiceImpl implements IResultManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(ResultManagementServiceImpl.class);
    
    @Autowired
    private ResultManagementMapper resultManagementMapper;
    @Autowired
    private IDbPhysicalManagementService dbPhysicalManagementService;
    @Autowired
    private IDbIdentityManagementService dbIdentityManagementService;
    @Autowired
    private IDbQualificationManagementService dbQualificationManagementService;
    @Autowired
    private IPhysicalManagementService physicalManagementService;
    @Autowired
    private IIdentityManagementService identityManagementService;
    @Autowired
    private IQualificationManagementService qualificationManagementService;
    @Autowired
    private IScoreManagementService scoreManagementService;



    /**
     * 查询四级联考终审结果
     * 
     * @param id 四级联考终审结果主键
     * @return 四级联考终审结果
     */
    @Override
    public ResultManagement selectResultManagementById(Long id)
    {
        return resultManagementMapper.selectResultManagementById(id);
    }

    /**
     * 查询四级联考终审结果列表
     * 
     * @param resultManagement 四级联考终审结果
     * @return 四级联考终审结果
     */
    @Override
    public List<ResultManagement> selectResultManagementList(ResultManagement resultManagement)
    {
        resultManagementMapper.deleteAllResultManagement();

//        QualificationManagement qualificationManagement = new QualificationManagement();
//        qualificationManagement.setQualificationReviewResult("未通过");
//        Set<String> qualificationSet = qualificationManagementService.selectQualificationManagementList(qualificationManagement).stream().map(QualificationManagement::getIdCard).collect(Collectors.toSet());
//        IdentityManagement identityManagement = new IdentityManagement();
//        identityManagement.setIdentityVerificationResult("未通过");
//        Set<String> identitySet = identityManagementService.selectIdentityManagementList(identityManagement).stream().map(IdentityManagement::getIdCard).collect(Collectors.toSet());
        PhysicalManagement physicalManagement = new PhysicalManagement();
        physicalManagement.setPhysicalTestResult("通过");
        Set<String> physicalSet = physicalManagementService.selectPhysicalManagementList(physicalManagement).stream().map(PhysicalManagement::getIdCard).collect(Collectors.toSet());
//        DbQualificationManagement dbQualificationManagement = new DbQualificationManagement();
//        dbQualificationManagement.setQualificationReviewResult("未通过");
//        Set<String> dbQhysicalSet = dbQualificationManagementService.selectDbQualificationManagementList(dbQualificationManagement).stream().map(DbQualificationManagement::getIdCard).collect(Collectors.toSet());
//        DbIdentityManagement dbIdentityManagement = new DbIdentityManagement();
//        dbIdentityManagement.setIdentityVerificationResult("未通过");
//        Set<String> dbIdentitySet = dbIdentityManagementService.selectDbIdentityManagementList(dbIdentityManagement).stream().map(DbIdentityManagement::getIdCard).collect(Collectors.toSet());
        DbPhysicalManagement dbPhysicalManagement = new DbPhysicalManagement();
        dbPhysicalManagement.setPhysicalTestResult("通过");
        Set<String> dbPhysicalSet = dbPhysicalManagementService.selectDbPhysicalManagementList(dbPhysicalManagement).stream().map(DbPhysicalManagement::getIdCard).collect(Collectors.toSet());
//        qualificationSet.addAll(identitySet);
//        qualificationSet.addAll(physicalSet);
//        qualificationSet.addAll(dbQhysicalSet);
//        qualificationSet.addAll(dbIdentitySet);
//        qualificationSet.addAll(dbPhysicalSet);

        physicalSet.addAll(dbPhysicalSet);

        List<ScoreManagement> scoreManagements = scoreManagementService.selectScoreManagementList(new ScoreManagement());
        for (ScoreManagement scoreManagement : scoreManagements) {
            if (physicalSet.contains(scoreManagement.getIdCard())) {
//                scoreManagement.setFinalResult("通过");

                ResultManagement management = new ResultManagement();
                management.setCandidateId(scoreManagement.getCandidateId());
                management.setName(scoreManagement.getName());
                management.setGender(scoreManagement.getGender());
                management.setIdCard(scoreManagement.getIdCard());
                management.setExamNumber(scoreManagement.getExamNumber());
                management.setAdministrativeAptitudeScore(scoreManagement.getAdministrativeAptitudeScore());
                management.setEssayScore(scoreManagement.getEssayScore());
                management.setProfessionalSubjectScore(scoreManagement.getProfessionalSubjectScore());
                management.setTotalScore(scoreManagement.getTotalScore());
                management.setProfessionalSkillTestScore(scoreManagement.getProfessionalSkillTestScore());
                management.setAppliedUnit(scoreManagement.getAppliedUnit());
                management.setAppliedPosition(scoreManagement.getAppliedPosition());
                management.setRecruitmentNumber(scoreManagement.getRecruitmentNumber());
                management.setInterviewRatio(scoreManagement.getInterviewRatio());
                management.setRanking(scoreManagement.getRanking());
                management.setGraduationSchool(scoreManagement.getGraduationSchool());
                management.setHasProfessionalSkillTest(scoreManagement.getHasProfessionalSkillTest());
                management.setPositionCategory(scoreManagement.getPositionCategory());
                management.setFinalResult("通过");

                if (dbPhysicalSet.contains(scoreManagement.getIdCard())) {
                    management.setIsAlternate("是");
                } else {
                    management.setIsAlternate("否");

                }
                resultManagementMapper.insertResultManagement(management);
            }
        }
//        scoreManagements.forEach(scoreManagement -> {
//            ResultManagement management = new ResultManagement();
//            management.setCandidateId(scoreManagement.getCandidateId());
//            management.setName(scoreManagement.getName());
//            management.setGender(scoreManagement.getGender());
//            management.setIdCard(scoreManagement.getIdCard());
//            management.setExamNumber(scoreManagement.getExamNumber());
//            management.setAdministrativeAptitudeScore(scoreManagement.getAdministrativeAptitudeScore());
//            management.setEssayScore(scoreManagement.getEssayScore());
//            management.setProfessionalSubjectScore(scoreManagement.getProfessionalSubjectScore());
//            management.setTotalScore(scoreManagement.getTotalScore());
//            management.setProfessionalSkillTestScore(scoreManagement.getProfessionalSkillTestScore());
//            management.setAppliedUnit(scoreManagement.getAppliedUnit());
//            management.setAppliedPosition(scoreManagement.getAppliedPosition());
//            management.setRecruitmentNumber(scoreManagement.getRecruitmentNumber());
//            management.setInterviewRatio(scoreManagement.getInterviewRatio());
//            management.setRanking(scoreManagement.getRanking());
//            management.setGraduationSchool(scoreManagement.getGraduationSchool());
//            management.setHasProfessionalSkillTest(scoreManagement.getHasProfessionalSkillTest());
//            management.setPositionCategory(scoreManagement.getPositionCategory());
//            management.setFinalResult(scoreManagement.getFinalResult());
//            resultManagementMapper.insertResultManagement(management);
//        });


        return resultManagementMapper.selectResultManagementList(resultManagement);
    }

    /**
     * 新增四级联考终审结果
     * 
     * @param resultManagement 四级联考终审结果
     * @return 结果
     */
    @Override
    public int insertResultManagement(ResultManagement resultManagement)
    {
        return resultManagementMapper.insertResultManagement(resultManagement);
    }

    /**
     * 修改四级联考终审结果
     * 
     * @param resultManagement 四级联考终审结果
     * @return 结果
     */
    @Override
    public int updateResultManagement(ResultManagement resultManagement)
    {
        return resultManagementMapper.updateResultManagement(resultManagement);
    }

    /**
     * 批量删除四级联考终审结果
     * 
     * @param ids 需要删除的四级联考终审结果主键
     * @return 结果
     */
    @Override
    public int deleteResultManagementByIds(Long[] ids)
    {
        return resultManagementMapper.deleteResultManagementByIds(ids);
    }

    /**
     * 删除四级联考终审结果信息
     * 
     * @param id 四级联考终审结果主键
     * @return 结果
     */
    @Override
    public int deleteResultManagementById(Long id)
    {
        return resultManagementMapper.deleteResultManagementById(id);
    }

    /**
     * 从体能测评名单生成并插入终审结果名单
     * 
     * @param physicalList 符合条件的体能测评名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertResultListFromPhysical(List<PhysicalManagement> physicalList, String operName)
    {
        if (StringUtils.isNull(physicalList) || physicalList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 遍历符合条件的考生，插入终审结果名单
        for (PhysicalManagement physical : physicalList)
        {
            try
            {
                // 创建终审结果名单对象
                ResultManagement result = new ResultManagement();
                
                // 复制考生信息
                result.setCandidateId(physical.getCandidateId());
                result.setName(physical.getName());
                result.setGender(physical.getGender());
                result.setIdCard(physical.getIdCard());
                result.setExamNumber(physical.getExamNumber());
                result.setAdministrativeAptitudeScore(physical.getAdministrativeAptitudeScore());
                result.setEssayScore(physical.getEssayScore());
                result.setProfessionalSubjectScore(physical.getProfessionalSubjectScore());
                result.setTotalScore(physical.getTotalScore());
                result.setProfessionalSkillTestScore(physical.getProfessionalSkillTestScore());
                result.setAppliedUnit(physical.getAppliedUnit());
                result.setAppliedPosition(physical.getAppliedPosition());
                result.setRecruitmentNumber(physical.getRecruitmentNumber());
                result.setInterviewRatio(physical.getInterviewRatio());
                result.setRanking(physical.getRanking());
                result.setGraduationSchool(physical.getGraduationSchool());
                result.setHasProfessionalSkillTest(physical.getHasProfessionalSkillTest());
                result.setPositionCategory(physical.getPositionCategory());
                result.setIsAlternate("N");  // 非递补
                result.setQualificationReviewResult(physical.getQualificationReviewResult());
                result.setIdentityVerificationResult(physical.getIdentityVerificationResult());
                result.setPhysicalTestResult(physical.getPhysicalTestResult());
                result.setFinalResult("通过");  // 设置最终结果为通过
                
                // 检查是否已经存在相同准考证号的记录
                ResultManagement existCheck = new ResultManagement();
                existCheck.setExamNumber(physical.getExamNumber());
                List<ResultManagement> existList = resultManagementMapper.selectResultManagementList(existCheck);
                
                if (existList == null || existList.size() == 0)
                {
                    // 插入终审结果名单
                    resultManagementMapper.insertResultManagement(result);
                    successNum++;
                    log.info("考生[" + physical.getName() + ", 准考证号:" + physical.getExamNumber() + "]已流转到终审结果");
                }
                else
                {
                    log.info("考生[" + physical.getName() + ", 准考证号:" + physical.getExamNumber() + "]已存在于终审结果名单中");
                }
            }
            catch (Exception e)
            {
                log.error("终审结果名单生成失败：", e);
                throw new ServiceException("生成终审结果名单失败，请联系管理员");
            }
        }
        
        return successNum;
    }
    
    /**
     * 从递补体能测评名单生成并插入终审结果名单
     * 
     * @param dbPhysicalList 符合条件的递补体能测评名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertResultListFromDbPhysical(List<DbPhysicalManagement> dbPhysicalList, String operName)
    {
        if (StringUtils.isNull(dbPhysicalList) || dbPhysicalList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 遍历符合条件的考生，插入终审结果名单
        for (DbPhysicalManagement dbPhysical : dbPhysicalList)
        {
            try
            {
                // 创建终审结果名单对象
                ResultManagement result = new ResultManagement();
                
                // 复制考生信息
                result.setCandidateId(dbPhysical.getCandidateId());
                result.setName(dbPhysical.getName());
                result.setGender(dbPhysical.getGender());
                result.setIdCard(dbPhysical.getIdCard());
                result.setExamNumber(dbPhysical.getExamNumber());
                result.setAdministrativeAptitudeScore(dbPhysical.getAdministrativeAptitudeScore());
                result.setEssayScore(dbPhysical.getEssayScore());
                result.setProfessionalSubjectScore(dbPhysical.getProfessionalSubjectScore());
                result.setTotalScore(dbPhysical.getTotalScore());
                result.setProfessionalSkillTestScore(dbPhysical.getProfessionalSkillTestScore());
                result.setAppliedUnit(dbPhysical.getAppliedUnit());
                result.setAppliedPosition(dbPhysical.getAppliedPosition());
                result.setRecruitmentNumber(dbPhysical.getRecruitmentNumber());
                result.setInterviewRatio(dbPhysical.getInterviewRatio());
                result.setRanking(dbPhysical.getRanking());
                result.setGraduationSchool(dbPhysical.getGraduationSchool());
                result.setHasProfessionalSkillTest(dbPhysical.getHasProfessionalSkillTest());
                result.setPositionCategory(dbPhysical.getPositionCategory());
                result.setIsAlternate("Y");  // 设置为递补
                result.setQualificationReviewResult(dbPhysical.getQualificationReviewResult());
                result.setIdentityVerificationResult(dbPhysical.getIdentityVerificationResult());
                result.setPhysicalTestResult(dbPhysical.getPhysicalTestResult());
                result.setFinalResult("通过");  // 设置最终结果为通过
                
                // 检查是否已经存在相同准考证号的记录
                ResultManagement existCheck = new ResultManagement();
                existCheck.setExamNumber(dbPhysical.getExamNumber());
                List<ResultManagement> existList = resultManagementMapper.selectResultManagementList(existCheck);
                
                if (existList == null || existList.size() == 0)
                {
                    // 插入终审结果名单
                    resultManagementMapper.insertResultManagement(result);
                    successNum++;
                    log.info("递补考生[" + dbPhysical.getName() + ", 准考证号:" + dbPhysical.getExamNumber() + "]已流转到终审结果");
                }
                else
                {
                    log.info("递补考生[" + dbPhysical.getName() + ", 准考证号:" + dbPhysical.getExamNumber() + "]已存在于终审结果名单中");
                }
            }
            catch (Exception e)
            {
                log.error("终审结果名单生成失败：", e);
                throw new ServiceException("生成终审结果名单失败，请联系管理员");
            }
        }
        
        return successNum;
    }

    /**
     * 获取四级联考终审结果统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getResultStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有终审结果数据
        List<ResultManagement> resultList = resultManagementMapper.selectResultManagementList(new ResultManagement());
        
        // 总数
        int total = resultList.size();
        statisticsDTO.setTotal(total);
        
        // 通过和未通过数量
        int passed = 0;
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (ResultManagement result : resultList)
        {
            // 统计通过人数
            if ("通过".equals(result.getFinalResult()))
            {
                passed++;
            }
            
            // 统计职位分布
            String position = result.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        statisticsDTO.setPassed(passed);
        statisticsDTO.setFailed(total - passed);
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
